<template>
  <div class="dormitory-check-app">
    <el-container>
      <el-header class="app-header">
        <div class="header-content">
          <h1>{{ currentMode === 'dormitory' ? '宿舍查寝系统' : '班级考勤系统' }}</h1>
          <div class="header-actions">
            <el-button type="primary" @click="showAddStudentDialog = true" size="default">
              <el-icon><Plus /></el-icon>添加学生
            </el-button>
            <el-button type="success" @click="showImportDialog = true" size="default">
              <el-icon><Upload /></el-icon>导入花名册
            </el-button>
            <el-select v-model="currentMode" placeholder="考勤类型" style="width: 120px" size="default">
              <el-option label="宿舍查寝" value="dormitory" />
              <el-option label="班级考勤" value="class" />
            </el-select>
            <el-button type="success" @click="startCheck" :disabled="isChecking" size="default">
              <el-icon><Clock /></el-icon>{{ isChecking ? (currentMode === 'dormitory' ? '查寝进行中...' : '考勤进行中...') : `开始${currentMode === 'dormitory' ? '查寝' : '考勤'}` }}
            </el-button>
            <el-button @click="showHistoryDialog = true" size="default">
              <el-icon><Document /></el-icon>历史记录
            </el-button>
            <el-button type="warning" @click="generateDailySummary" size="default">
              <el-icon><DataAnalysis /></el-icon>日总结
            </el-button>
            <el-button type="info" @click="generateWeeklySummary" size="default">
              <el-icon><TrendCharts /></el-icon>周总结
            </el-button>
            <!-- 保存数据按钮已移除，改为自动保存逻辑 -->

            <el-button type="primary" @click="goToClassAttendance" size="default">
              <el-icon><User /></el-icon>{{ currentMode === 'dormitory' ? '切换到班级考勤' : '切换到宿舍查寝' }}
            </el-button>
            <el-button type="danger" @click="clearAllData" :disabled="currentStudents.length === 0" size="default">
              <el-icon><Delete /></el-icon>清空列表
            </el-button>
            <el-button :type="isDarkTheme ? 'warning' : 'info'" @click="toggleTheme" size="default">
              <el-icon><component :is="isDarkTheme ? Sunny : Moon" /></el-icon>{{ isDarkTheme ? '明亮主题' : '暗黑主题' }}
            </el-button>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <!-- 统计信息 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :xs="24" :sm="12" :md="6" :lg="4" :xl="4">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">👥</div>
              <div class="stat-number">{{ currentStudents.length }}</div>
              <div class="stat-label">总人数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="5" :xl="5">
          <el-card class="stat-card present">
            <div class="stat-item">
              <div class="stat-icon">✅</div>
              <div class="stat-number">{{ presentCount }}</div>
              <div class="stat-label">{{ currentMode === 'dormitory' ? '在寝人数' : '出勤人数' }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="5" :xl="5">
          <el-card class="stat-card absent">
            <div class="stat-item">
              <div class="stat-icon">❌</div>
              <div class="stat-number">{{ absentCount }}</div>
              <div class="stat-label">缺勤人数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="5" :xl="5">
          <el-card class="stat-card leave">
            <div class="stat-item">
              <div class="stat-icon">📋</div>
              <div class="stat-number">{{ leaveCount }}</div>
              <div class="stat-label">请假人数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="5" :xl="5">
          <el-card class="stat-card delay">
            <div class="stat-item">
              <div class="stat-icon">⏰</div>
              <div class="stat-number">{{ delayCount }}</div>
              <div class="stat-label">{{ currentMode === 'dormitory' ? '晚归人数' : '迟到人数' }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 按寝室分排视图（仅在宿舍查寝模式下显示） -->
      <el-card class="room-arrangement-card" v-if="currentMode === 'dormitory'" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>按寝室分排</span>
            <div class="progress-info" v-if="isChecking">
              <el-progress 
                :percentage="checkProgress" 
                :stroke-width="6"
                :status="checkProgress === 100 ? 'success' : 'text'"
                style="width: 150px; margin-right: 10px;"
              />
              <span class="progress-text">{{ checkProgress }}%</span>
            </div>
            <el-button type="primary" size="small" @click="showRoomArrangement = !showRoomArrangement">
              {{ showRoomArrangement ? '收起' : '展开' }}
            </el-button>
          </div>
        </template>
        
        <el-collapse-transition>
          <div v-show="showRoomArrangement">
            <el-row :gutter="10" class="room-filter-row">
              <el-col :span="8">
                <el-select v-model="selectedRoom" placeholder="选择寝室" clearable @change="filterByRoom">
                  <el-option
                    v-for="room in uniqueRooms"
                    :key="room"
                    :label="room"
                    :value="room"
                  />
                </el-select>
              </el-col>
              <el-col :span="16">
                <el-button-group>
                  <el-button type="success" size="small" @click="setRoomStatus('present')">
                    全寝在寝
                  </el-button>
                  <el-button type="warning" size="small" @click="setRoomStatus('leave')">
                    全寝请假
                  </el-button>
                  <el-button type="danger" size="small" @click="setRoomStatus('absent')">
                    全寝缺勤
                  </el-button>
                  <el-button type="info" size="small" @click="setRoomStatus('delay')">
                    全寝晚归
                  </el-button>
                </el-button-group>
              </el-col>
            </el-row>

            <!-- 寝室分排展示 -->
            <el-row :gutter="20" class="room-display-row">
              <el-col :span="8" v-for="room in displayedRooms" :key="room" class="room-column">
                <el-card class="room-card" shadow="hover">
                  <template #header>
                    <div class="room-header">
                      <span class="room-number">{{ room }}</span>
                      <el-tag 
                        :type="getRoomStatusType(room)" 
                        size="small"
                        effect="dark"
                      >
                        {{ getRoomStatusText(room) }}
                      </el-tag>
                    </div>
                    <div class="room-stats" v-if="isChecking">
                      <el-tag type="info" size="mini">
                        共{{ getRoomStats(room).total }}人
                      </el-tag>
                      <el-tag type="success" size="mini" v-if="getRoomStats(room).checked > 0">
                        已检{{ getRoomStats(room).checked }}人
                      </el-tag>
                      <el-tag type="warning" size="mini" v-if="getRoomStats(room).unchecked > 0">
                        待检{{ getRoomStats(room).unchecked }}人
                      </el-tag>
                      <el-tag type="success" size="mini" v-if="getRoomStats(room).present > 0">
                        在寝{{ getRoomStats(room).present }}人
                      </el-tag>
                      <el-tag type="danger" size="mini" v-if="getRoomStats(room).absent > 0">
                        缺勤{{ getRoomStats(room).absent }}人
                      </el-tag>
                    </div>
                  </template>
                  
                  <div class="room-students">
                    <div 
                      v-for="student in getStudentsByRoom(room)" 
                      :key="student.id"
                      class="room-student-item"
                    >
                      <el-tag :type="getStatusType(student.checkStatus)" size="small">
                        {{ student.name }}
                      </el-tag>
                    </div>
                  </div>
                  
                  <div class="room-actions">
                    <el-button-group size="mini">
                      <el-button 
                        type="success" 
                        @click="setSpecificRoomStatus(room, 'present')"
                        :disabled="!isChecking"
                      >
                        在寝
                      </el-button>
                      <el-button 
                        type="warning" 
                        @click="setSpecificRoomStatus(room, 'leave')"
                        :disabled="!isChecking"
                      >
                        请假
                      </el-button>
                      <el-button 
                        type="danger" 
                        @click="setSpecificRoomStatus(room, 'absent')"
                        :disabled="!isChecking"
                      >
                        缺勤
                      </el-button>
                    </el-button-group>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-collapse-transition>
      </el-card>

        <!-- 批量操作栏 -->
        <div class="batch-operation-bar" v-if="isChecking">
          <div class="batch-actions">
            <div class="quick-actions-group">
              <span class="quick-actions-title">🚀 一键操作</span>
              <div class="quick-actions-buttons">
                <el-button type="success" size="default" @click="batchSetStatus('present')" class="quick-action-btn">
                  <el-icon><Check /></el-icon>一键实到
                </el-button>
                <el-button type="warning" size="default" @click="batchSetStatus('leave')" class="quick-action-btn">
                  <el-icon><Clock /></el-icon>一键请假
                </el-button>
                <el-button type="danger" size="default" @click="batchSetStatus('absent')" class="quick-action-btn">
                  <el-icon><Close /></el-icon>一键缺勤
                </el-button>
                <el-button type="info" size="default" @click="batchSetStatus('delay')" class="quick-action-btn">
                  <el-icon><Clock /></el-icon>一键{{ currentMode === 'dormitory' ? '晚归' : '迟到' }}
                </el-button>
              </div>
            </div>
            <div class="finish-action-group">
              <el-button type="success" size="large" @click="finishCheck" class="finish-check-btn">
                <el-icon><Check /></el-icon>完成{{ currentMode === 'dormitory' ? '查寝' : '考勤' }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 学生列表 -->
        <el-card class="student-list-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">📋 {{ currentMode === 'dormitory' ? '晚上查寝' : '上课考勤' }} - 学生列表</span>
              <div class="header-actions">
                <!-- 显示当前筛选状态 -->
                <el-tag 
                  v-if="selectedRoom && currentMode === 'dormitory'" 
                  type="info" 
                  closable
                  @close="clearRoomFilter"
                  style="margin-right: 10px;"
                >
                  🏠 {{ selectedRoom }}
                </el-tag>
                <el-input
                  v-model="searchQuery"
                  placeholder="🔍 搜索学生姓名或学号"
                  style="width: 250px"
                  clearable
                  class="search-input"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
            </div>
          </template>
          
          <el-table :data="filteredStudents" style="width: 100%" @selection-change="handleSelectionChange" class="student-table">
            <el-table-column type="selection" width="55" v-if="isChecking" />
            <el-table-column prop="studentId" label="学号" width="120">
              <template #default="{ row }">
                <span class="student-id">{{ row.studentId }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="120">
              <template #default="{ row }">
                <span class="student-name">{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="dormitory" label="宿舍" width="120" v-if="currentMode === 'dormitory'">
              <template #default="{ row }">
                <span class="dormitory-number">🏠 {{ row.dormitory }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="contact" label="联系方式" width="150" />
            <el-table-column label="考勤状态" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.checkStatus)" effect="dark" class="status-tag">
                  {{ getStatusText(row.checkStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button-group>
                  <el-button size="small" @click="editStudent(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteStudent(row)">删除</el-button>
                </el-button-group>
              </template>
            </el-table-column>
            <el-table-column label="快速操作" width="320" align="center">
              <template #default="{ row }">
                <el-button-group class="quick-action-group">
                  <el-button 
                    size="small" 
                    type="success" 
                    @click="setCheckStatus(row, 'present')"
                    :disabled="!isChecking"
                    class="quick-btn present-btn"
                  >
                    ✅ 实到
                  </el-button>
                  <el-button 
                    size="small" 
                    type="warning" 
                    @click="setCheckStatus(row, 'leave')"
                    :disabled="!isChecking"
                    class="quick-btn leave-btn"
                  >
                    📋 请假
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="setCheckStatus(row, 'absent')"
                    :disabled="!isChecking"
                    class="quick-btn absent-btn"
                  >
                    ❌ 缺勤
                  </el-button>
                  <el-button 
                    size="small" 
                    type="info" 
                    @click="setCheckStatus(row, 'delay')"
                    :disabled="!isChecking"
                    class="quick-btn delay-btn"
                  >
                    ⏰ {{ currentMode === 'dormitory' ? '晚归' : '迟到' }}
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-main>
    </el-container>

    <!-- 添加学生对话框 -->
    <el-dialog
      v-model="showAddStudentDialog"
      :title="editingStudent ? '编辑学生' : '添加学生'"
      width="400px"
    >
      <el-form :model="studentForm" label-width="80px">
        <el-form-item label="学号">
          <el-input v-model="studentForm.studentId" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="studentForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="宿舍号" v-if="currentMode === 'dormitory'">
          <el-input v-model="studentForm.dormitory" placeholder="请输入宿舍号" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="studentForm.contact" placeholder="请输入联系方式" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddStudentDialog = false">取消</el-button>
        <el-button type="primary" @click="saveStudent">保存</el-button>
      </template>
    </el-dialog>

    <!-- 历史记录详情对话框 -->
    <el-dialog
      v-model="showHistoryDetailDialog"
      title="查寝详情"
      width="600px"
    >
      <div v-if="selectedHistoryRecord">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日期">{{ selectedHistoryRecord.date }}</el-descriptions-item>
          <el-descriptions-item label="时间">{{ selectedHistoryRecord.time }}</el-descriptions-item>
          <el-descriptions-item label="总人数">{{ selectedHistoryRecord.total }}人</el-descriptions-item>
          <el-descriptions-item label="查寝人">{{ selectedHistoryRecord.checker }}</el-descriptions-item>
          <el-descriptions-item label="实到人数">
            <el-tag type="success">{{ selectedHistoryRecord.present }}人</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="请假人数">
            <el-tag type="warning">{{ selectedHistoryRecord.leave }}人</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="缺勤人数">
            <el-tag type="danger">{{ selectedHistoryRecord.absent }}人</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="迟到人数">
            <el-tag type="info">{{ selectedHistoryRecord.delay }}人</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="晚归人数">
            <el-tag type="info">{{ selectedHistoryRecord.late }}人</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div style="margin-top: 20px;">
          <h4>详细名单</h4>
          <el-table :data="selectedHistoryRecord.students" style="width: 100%">
            <el-table-column prop="studentId" label="学号" width="100" />
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column label="状态">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 总结对话框 -->
    <el-dialog
      :title="currentMode === 'dormitory' ? (summaryType === 'daily' ? '查寝日总结' : '查寝周总结') : (summaryType === 'daily' ? '上课日总结' : '上课周总结')"
      v-model="showSummaryDialog"
      width="600px"
    >
      <div class="summary-content" v-if="summaryData">
        <!-- 日总结 -->
        <div v-if="summaryType === 'daily'" class="daily-summary">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="日期">{{ summaryData.date }}</el-descriptions-item>
            <el-descriptions-item label="总人数">{{ summaryData.total }}人</el-descriptions-item>
            <el-descriptions-item label="在寝人数">
              <el-tag type="success">{{ summaryData.present }}人</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="缺勤人数">
              <el-tag type="danger">{{ summaryData.absent }}人</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="请假人数">
              <el-tag type="warning">{{ summaryData.leave }}人</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="迟到人数">
              <el-tag type="info">{{ summaryData.delay }}人</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="晚归人数">
              <el-tag type="info">{{ summaryData.late }}人</el-tag>
            </el-descriptions-item>
          </el-descriptions>
          
          <!-- 请假学生详细信息 -->
          <div v-if="summaryData.leaveStudents && summaryData.leaveStudents.length > 0" class="leave-students-info" style="margin-top: 20px;">
            <h4>请假学生名单</h4>
            <el-table :data="summaryData.leaveStudents" style="width: 100%" size="small">
              <el-table-column prop="dormitory" label="寝室号" width="100" v-if="currentMode === 'dormitory'" />
              <el-table-column prop="name" label="姓名" width="100" />
              <el-table-column prop="studentId" label="学号" width="120" />
            </el-table>
          </div>
          
          <div class="summary-chart" style="margin-top: 20px;">
            <h4>状态分布</h4>
            <el-progress :percentage="Math.round((summaryData.present / summaryData.total) * 100)" status="success">
              <span>在寝 {{summaryData.present}}人</span>
            </el-progress>
            <el-progress :percentage="Math.round((summaryData.absent / summaryData.total) * 100)" status="exception">
              <span>缺勤 {{summaryData.absent}}人</span>
            </el-progress>
            <el-progress :percentage="Math.round((summaryData.leave / summaryData.total) * 100)" status="warning">
              <span>请假 {{summaryData.leave}}人</span>
            </el-progress>
            <el-progress :percentage="Math.round((summaryData.delay / summaryData.total) * 100)">
              <span>迟到 {{summaryData.delay}}人</span>
            </el-progress>
            <el-progress :percentage="Math.round((summaryData.late / summaryData.total) * 100)">
              <span>晚归 {{summaryData.late}}人</span>
            </el-progress>
          </div>
        </div>
        
        <!-- 周总结 -->
        <div v-else class="weekly-summary">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="统计周期">{{ summaryData.startDate }} 至 {{ summaryData.endDate }}</el-descriptions-item>
            <el-descriptions-item label="查寝次数">{{ summaryData.totalChecks }}次</el-descriptions-item>
            <el-descriptions-item label="平均在寝人数">
              <el-tag type="success">{{ summaryData.avgPresent }}人</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="平均缺勤人数">
              <el-tag type="danger">{{ summaryData.avgAbsent }}人</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="平均请假人数">
              <el-tag type="warning">{{ summaryData.avgLeave }}人</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="平均迟到人数">
              <el-tag type="info">{{ summaryData.avgDelay }}人</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="平均晚归人数">
              <el-tag type="info">{{ summaryData.avgLate }}人</el-tag>
            </el-descriptions-item>
          </el-descriptions>
          
          <div class="weekly-chart" style="margin-top: 20px;">
            <h4>一周趋势</h4>
            <el-table :data="summaryData.records" style="width: 100%">
              <el-table-column prop="date" label="日期" width="120"></el-table-column>
              <el-table-column prop="present" label="在寝" width="80">
                <template #default="{ row }">
                  <el-tag type="success" size="small">{{ row.present }}人</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="absent" label="缺勤" width="80">
                <template #default="{ row }">
                  <el-tag type="danger" size="small">{{ row.absent }}人</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="leave" label="请假" width="80">
                <template #default="{ row }">
                  <el-tag type="warning" size="small">{{ row.leave }}人</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="late" label="晚归" width="80">
                <template #default="{ row }">
                  <el-tag type="info" size="small">{{ row.late }}人</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showSummaryDialog = false">关闭</el-button>
        <el-button type="primary" @click="exportSummary">导出总结</el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="showHistoryDialog"
      :title="currentMode === 'dormitory' ? '晚上查寝历史记录' : '上课考勤历史记录'"
      width="800px"
    >
      <el-table :data="currentHistory" style="width: 100%">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="time" label="时间" width="100" />
        <el-table-column label="考勤类型" width="100">
          <template #default="{ row }">
            {{row.type === 'morning' ? '上课考勤' : '晚上查寝'}}
          </template>
        </el-table-column>
        <el-table-column prop="total" label="总人数" width="80" />
        <el-table-column prop="present" label="实到" width="80" />
        <el-table-column prop="leave" label="请假" width="80" />
        <el-table-column prop="absent" label="缺勤" width="80" />
        <el-table-column prop="checker" label="查寝人" width="100" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button size="small" @click="viewHistoryDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- Excel导入对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="导入班级花名册"
      width="500px"
    >
      <div>
        <p style="margin-bottom: 20px;">请上传Excel文件，格式要求：</p>
        <el-table :data="importFormat" style="width: 100%; margin-bottom: 20px;">
          <el-table-column prop="col1" label="宿舍号" width="120" v-if="currentMode === 'dormitory'" />
          <el-table-column prop="col2" label="姓名" width="120" />
          <el-table-column prop="col3" label="学号" width="120" />
          <el-table-column prop="col4" label="联系方式" width="120" />
        </el-table>
        <input 
          type="file" 
          ref="fileInput" 
          accept=".xlsx,.xls" 
          style="display: none"
          @change="handleFileUpload"
        />
        <el-button type="primary" @click="$refs.fileInput.click()">
          <el-icon><Upload /></el-icon>选择Excel文件
        </el-button>
        <div v-if="importResult" style="margin-top: 20px;">
          <el-alert
            :title="importResult.message"
            :type="importResult.success ? 'success' : 'error'"
            :closable="false"
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="showImportDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmImport" :disabled="!importData.length">
          确认导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Sunny, Moon } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import * as XLSX from 'xlsx'

// 路由实例
const router = useRouter()

// 当前模式状态
const currentMode = ref('dormitory') // 'dormitory' 或 'class'
const isChecking = ref(false)
const searchQuery = ref('')
const showAddStudentDialog = ref(false)
const showImportDialog = ref(false)
const showHistoryDialog = ref(false)
const showHistoryDetailDialog = ref(false)
const editingStudent = ref(null)
const selectedHistoryRecord = ref(null)

// 宿舍查寝数据
const dormitoryStudents = ref([])
const dormitoryHistory = ref([])

// 班级考勤数据
const classStudents = ref([])
const classHistory = ref([])

// Excel导入相关
const importData = ref([])
const importResult = ref(null)
const importFormat = computed(() => {
  if (currentMode.value === 'dormitory') {
    return []
  } else {
    return []
  }
})

// 批量操作相关
const selectAll = ref(false)
const selectedStudents = ref([])

// 总结功能相关
const showSummaryDialog = ref(false)
const summaryType = ref('daily') // 'daily' 或 'weekly'
const summaryData = ref(null)

// 未保存更改状态
const hasUnsavedChanges = ref(false)

// 按寝室分排相关
const showRoomArrangement = ref(localStorage.getItem('showRoomArrangement') !== 'false')
const selectedRoom = ref('')

// 主题相关
const isDarkTheme = ref(localStorage.getItem('darkTheme') === 'true')

// 学生表单
const studentForm = ref({
  studentId: '',
  name: '',
  dormitory: '',
  contact: ''
})

// 计算属性 - 根据当前模式返回相应数据
const currentStudents = computed(() => {
  return currentMode.value === 'dormitory' ? dormitoryStudents.value : classStudents.value
})

const currentHistory = computed(() => {
  return currentMode.value === 'dormitory' ? dormitoryHistory.value : classHistory.value
})

const filteredStudents = computed(() => {
  let students = currentStudents.value
  
  // 如果选择了特定寝室，先按寝室筛选
  if (selectedRoom.value && currentMode.value === 'dormitory') {
    students = students.filter(student => student.dormitory === selectedRoom.value)
  }
  
  // 如果有搜索查询，再按姓名或学号筛选
  if (searchQuery.value) {
    students = students.filter(student => 
      student.name.includes(searchQuery.value) || 
      student.studentId.includes(searchQuery.value)
    )
  }
  
  return students
})

const presentCount = computed(() => {
  return currentStudents.value.filter(s => s.checkStatus === 'present').length
})

const absentCount = computed(() => {
  return currentStudents.value.filter(s => s.checkStatus === 'absent').length
})

const leaveCount = computed(() => {
  return currentStudents.value.filter(s => s.checkStatus === 'leave').length
})

const uncheckedCount = computed(() => {
  return currentStudents.value.filter(s => s.checkStatus === 'unchecked').length
})

// 查寝进度百分比
const checkProgress = computed(() => {
  if (currentStudents.value.length === 0) return 0
  const checkedCount = currentStudents.value.filter(s => s.checkStatus !== 'unchecked').length
  return Math.round((checkedCount / currentStudents.value.length) * 100)
})

const delayCount = computed(() => {
  return currentStudents.value.filter(s => s.checkStatus === 'delay').length
})

// 获取所有唯一的寝室号（仅在宿舍查寝模式下）
const uniqueRooms = computed(() => {
  if (currentMode.value !== 'dormitory') return []
  const rooms = new Set(currentStudents.value.map(s => s.dormitory).filter(Boolean))
  return Array.from(rooms).sort()
})

// 显示的寝室列表
const displayedRooms = computed(() => {
  if (selectedRoom.value) {
    return [selectedRoom.value]
  }
  return uniqueRooms.value
})

// 方法
const getStatusType = (status) => {
  const types = {
    present: 'success',
    absent: 'danger',
    leave: 'warning',
    delay: 'info',
    unchecked: 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    present: '实到',
    absent: '缺勤',
    leave: '请假',
    late: '晚归',
    delay: currentMode.value === 'dormitory' ? '晚归' : '迟到',
    unchecked: '未检查'
  }
  return texts[status] || '未检查'
}

const startCheck = () => {
  isChecking.value = true
  // 重置当前模式所有学生的检查状态
  currentStudents.value.forEach(student => {
    student.checkStatus = 'unchecked'
  })
  
  // 如果是宿舍查寝模式，自动展开按寝室分排视图
  if (currentMode.value === 'dormitory') {
    showRoomArrangement.value = true
  }
  
  ElMessage({
    message: `${currentMode.value === 'dormitory' ? '查寝' : '考勤'}开始！请依次确认每位同学的状态`,
    type: 'success'
  })
}

const setCheckStatus = (student, status) => {
  student.checkStatus = status
  
  // 只有在手动点击"完成查寝"按钮时才自动完成
  // 单个状态修改只标记未保存状态，不自动完成
  hasUnsavedChanges.value = true
}

// 批量设置状态
const batchSetStatus = (status) => {
  if (selectedStudents.value.length === 0) {
    ElMessage.warning('请先选择学生')
    return
  }
  
  selectedStudents.value.forEach(student => {
    student.checkStatus = status
  })
  
  ElMessage.success(`已将 ${selectedStudents.value.length} 名学生状态设置为${getStatusText(status)}`)
  hasUnsavedChanges.value = true
}

// 全选/取消全选
const handleSelectAll = (val) => {
  const table = document.querySelector('.student-list-card .el-table')
  if (table) {
    const tableComponent = table.__vueParentComponent
    if (tableComponent) {
      if (val) {
        tableComponent.toggleAllSelection()
      } else {
        tableComponent.clearSelection()
      }
    }
  }
}

// 选择变化处理
const handleSelectionChange = (val) => {
  selectedStudents.value = val
}

const finishCheck = () => {
  if (!isChecking.value) return
  
  const presentCount = currentStudents.value.filter(s => s.checkStatus === 'present').length
  const leaveCount = currentStudents.value.filter(s => s.checkStatus === 'leave').length
  const absentCount = currentStudents.value.filter(s => s.checkStatus === 'absent').length
  const delayCount = currentStudents.value.filter(s => s.checkStatus === 'delay').length
  const totalCount = currentStudents.value.length
  
  // 检查是否所有学生都已检查
  const uncheckedCount = currentStudents.value.filter(s => s.checkStatus === 'unchecked').length
  
  if (uncheckedCount > 0) {
    ElMessageBox.confirm(
      `还有 ${uncheckedCount} 名学生未检查，是否继续完成查寝？`,
      '提示',
      {
        confirmButtonText: '继续完成',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      saveCheckRecord(presentCount, leaveCount, absentCount, 0, delayCount, totalCount)
    }).catch(() => {
      // 用户取消，不做任何操作
    })
  } else {
    saveCheckRecord(presentCount, leaveCount, absentCount, 0, delayCount, totalCount)
  }
}

const saveStudent = () => {
  if (!studentForm.value.studentId || !studentForm.value.name) {
    ElMessage({
      message: '请填写完整的学生信息',
      type: 'warning'
    })
    return
  }
  
  if (editingStudent.value) {
    // 编辑模式
    Object.assign(editingStudent.value, studentForm.value)
  } else {
    // 添加模式
    currentStudents.value.push({
      ...studentForm.value,
      checkStatus: 'unchecked'
    })
  }
  
  showAddStudentDialog.value = false
  resetStudentForm()
  hasUnsavedChanges.value = true
  
  ElMessage({
    message: editingStudent.value ? '学生信息已更新' : '学生添加成功',
    type: 'success'
  })
}

const editStudent = (student) => {
  editingStudent.value = student
  studentForm.value = { ...student }
  showAddStudentDialog.value = true
}

const deleteStudent = (student) => {
  ElMessageBox.confirm(
    `确定要删除学生 ${student.name} 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = currentStudents.value.indexOf(student)
    if (index > -1) {
      currentStudents.value.splice(index, 1)
      hasUnsavedChanges.value = true
      ElMessage({
        message: '学生删除成功',
        type: 'success'
      })
    }
  })
}

const resetStudentForm = () => {
  studentForm.value = {
    studentId: '',
    name: '',
    dormitory: ''
  }
  editingStudent.value = null
}

const viewHistoryDetail = (record) => {
  selectedHistoryRecord.value = record
  showHistoryDetailDialog.value = true
}

// 数据持久化
const saveCurrentData = () => {
  if (currentMode.value === 'dormitory') {
    localStorage.setItem('dormitoryStudents', JSON.stringify(dormitoryStudents.value))
    localStorage.setItem('dormitoryHistory', JSON.stringify(dormitoryHistory.value))
  } else {
    localStorage.setItem('classStudents', JSON.stringify(classStudents.value))
    localStorage.setItem('classHistory', JSON.stringify(classHistory.value))
  }
  hasUnsavedChanges.value = false
  ElMessage.success('数据保存成功！')
}

const loadData = () => {
  // 加载宿舍数据
  const savedDormitoryStudents = localStorage.getItem('dormitoryStudents')
  const savedDormitoryHistory = localStorage.getItem('dormitoryHistory')
  
  if (savedDormitoryStudents) {
    dormitoryStudents.value = JSON.parse(savedDormitoryStudents)
  } else {
    // 初始化为空数组，无示例数据
    dormitoryStudents.value = []
  }
  
  if (savedDormitoryHistory) {
    dormitoryHistory.value = JSON.parse(savedDormitoryHistory)
  }
  
  // 加载班级数据
  const savedClassStudents = localStorage.getItem('classStudents')
  const savedClassHistory = localStorage.getItem('classHistory')
  
  if (savedClassStudents) {
    classStudents.value = JSON.parse(savedClassStudents)
  } else {
    // 默认空数据，用户需要导入或手动添加
    classStudents.value = []
  }
  
  if (savedClassHistory) {
    classHistory.value = JSON.parse(savedClassHistory)
  }
}





// 保存查寝记录
const saveCheckRecord = (presentCount, leaveCount, absentCount, lateCount, delayCount, totalCount) => {
  isChecking.value = false
  
  // 获取当前时间
  const currentTime = new Date()
  const currentDate = currentTime.toLocaleDateString('zh-CN')
  const currentTimeStr = currentTime.toLocaleTimeString()
  
  // 保存查寝记录，包含更详细的信息
  const record = {
    date: currentDate,
    time: currentTimeStr,
    timestamp: currentTime.getTime(), // 添加时间戳用于排序
    total: totalCount,
    present: presentCount,
    leave: leaveCount,
    absent: absentCount,
    late: 0, // 不再使用late状态
    delay: delayCount,
    checker: '考勤班长',
    type: currentMode.value, // 'dormitory' 或 'class'
    students: currentStudents.value.map(s => ({
      studentId: s.studentId,
      name: s.name,
      dormitory: s.dormitory,
      status: s.checkStatus
    }))
  }
  
  // 添加到对应模式的历史记录
  if (currentMode.value === 'dormitory') {
    dormitoryHistory.value.unshift(record)
  } else {
    classHistory.value.unshift(record)
  }
  
  // 标记有未保存的更改
  hasUnsavedChanges.value = true
  
  // 显示完成消息
  ElMessage({
    message: `${currentMode.value === 'dormitory' ? '查寝' : '班级考勤'}完成！实到${presentCount}人，请假${leaveCount}人，缺勤${absentCount}人，${currentMode.value === 'dormitory' ? '晚归' : '迟到'}${delayCount}人`
  })
  
  // 完成查寝后自动收起按寝室分排视图
  if (currentMode.value === 'dormitory') {
    showRoomArrangement.value = false
  }
}

// 按寝室筛选
const filterByRoom = () => {
  // 筛选逻辑由 displayedRooms 计算属性处理
  // 保存用户偏好
  localStorage.setItem('showRoomArrangement', showRoomArrangement.value.toString())
}

// 清空寝室筛选
const clearRoomFilter = () => {
  selectedRoom.value = ''
  ElMessage.success('已清空寝室筛选')
}

// 主题切换
const toggleTheme = () => {
  isDarkTheme.value = !isDarkTheme.value
  localStorage.setItem('darkTheme', isDarkTheme.value.toString())
  applyTheme()
  ElMessage.success(isDarkTheme.value ? '已切换到暗黑主题' : '已切换到明亮主题')
}

// 应用主题
const applyTheme = () => {
  if (isDarkTheme.value) {
    document.body.classList.add('dark-theme')
  } else {
    document.body.classList.remove('dark-theme')
  }
}

// 获取指定寝室的学生
const getStudentsByRoom = (room) => {
  return currentStudents.value.filter(s => s.dormitory === room)
}

// 获取寝室统计信息
const getRoomStats = (roomNumber) => {
  const roomStudents = getStudentsByRoom(roomNumber)
  const stats = {
    total: roomStudents.length,
    checked: 0,
    unchecked: 0,
    present: 0,
    absent: 0
  }
  
  roomStudents.forEach(student => {
    if (student.checkStatus === 'unchecked') {
      stats.unchecked++
    } else {
      stats.checked++
      if (student.checkStatus === 'present') {
        stats.present++
      } else if (student.checkStatus === 'absent') {
        stats.absent++
      }
    }
  })
  
  return stats
}

// 获取寝室状态类型
const getRoomStatusType = (room) => {
  const students = getStudentsByRoom(room)
  if (students.length === 0) return 'info'
  
  const hasAbsent = students.some(s => s.checkStatus === 'absent')
  const hasUnchecked = students.some(s => s.checkStatus === 'unchecked')
  const allPresent = students.every(s => s.checkStatus === 'present')
  
  if (hasAbsent) return 'danger'
  if (hasUnchecked) return 'info'
  if (allPresent) return 'success'
  return 'warning'
}

// 获取寝室状态文本
const getRoomStatusText = (room) => {
  const students = getStudentsByRoom(room)
  if (students.length === 0) return '空寝'
  
  const statusCounts = {
    present: students.filter(s => s.checkStatus === 'present').length,
    absent: students.filter(s => s.checkStatus === 'absent').length,
    leave: students.filter(s => s.checkStatus === 'leave').length,
    delay: students.filter(s => s.checkStatus === 'delay').length,
    unchecked: students.filter(s => s.checkStatus === 'unchecked').length
  }
  
  if (statusCounts.unchecked === students.length) return '未检查'
  if (statusCounts.present === students.length) return '全寝在寝'
  if (statusCounts.absent === students.length) return '全寝缺勤'
  if (statusCounts.leave === students.length) return '全寝请假'
  
  return `${statusCounts.present}在 ${statusCounts.absent}缺 ${statusCounts.leave}假`
}

// 设置指定寝室的状态
const setRoomStatus = (status) => {
  if (!selectedRoom.value) {
    ElMessage.warning('请先选择寝室')
    return
  }
  
  const students = getStudentsByRoom(selectedRoom.value)
  if (students.length === 0) {
    ElMessage.warning('该寝室没有学生')
    return
  }
  
  students.forEach(student => {
    student.checkStatus = status
  })
  
  hasUnsavedChanges.value = true
  saveCurrentData() // 自动保存进度
  ElMessage.success(`已将${selectedRoom.value}寝室的${students.length}名学生设置为${getStatusText(status)}`)
}

// 设置特定寝室的状态（用于寝室卡片操作）
const setSpecificRoomStatus = (room, status) => {
  if (!isChecking.value) {
    ElMessage.warning('请先开始查寝')
    return
  }
  
  const students = getStudentsByRoom(room)
  if (students.length === 0) {
    ElMessage.warning('该寝室没有学生')
    return
  }
  
  students.forEach(student => {
    student.checkStatus = status
  })
  
  hasUnsavedChanges.value = true
  saveCurrentData() // 自动保存进度
  ElMessage.success(`已将${room}寝室的${students.length}名学生设置为${getStatusText(status)}`)
}

// 一键清空列表数据
const clearAllData = () => {
  ElMessageBox.confirm(
    `⚠️ 警告：此操作将清空所有数据！\n\n将要清空的内容：\n• 所有学生数据\n• 所有查寝/考勤记录\n• 所有日总结和周总结数据\n• 所有统计信息\n\n此操作不可恢复，请谨慎操作！`,
    '⚠️ 终极警告 - 清空所有数据',
    {
      confirmButtonText: '我已知晓，确认清空',
      cancelButtonText: '取消操作',
      type: 'error',
      confirmButtonClass: 'el-button--danger',
      dangerouslyUseHTMLString: true
    }
  ).then(() => {
    // 二级确认 - 使用prompt让用户输入确认文字
    return ElMessageBox.prompt(
      '🚨 最后确认：\n\n您确定要执行此操作吗？\n所有数据将被永久删除！\n\n请输入 <strong>"确认清空"</strong> 以继续操作：',
      '🚨 最终确认',
      {
        confirmButtonText: '确认清空',
        cancelButtonText: '取消',
        type: 'error',
        confirmButtonClass: 'el-button--danger',
        dangerouslyUseHTMLString: true,
        inputPattern: /^确认清空$/,
        inputErrorMessage: '输入错误，请输入"确认清空"以继续'
      }
    )
  }).then(() => {
    // 执行清空操作 - 清空所有数据
    dormitoryStudents.value = []
    classStudents.value = []
    dormitoryHistory.value = []
    classHistory.value = []
    
    hasUnsavedChanges.value = true
    
    ElMessage({
      message: '✅ 所有数据已清空，系统已重置为初始状态',
      type: 'success'
    })
  }).catch(() => {
    // 用户取消操作
    ElMessage({
      message: '已取消清空操作，数据未受影响',
      type: 'info'
    })
  })
}

// 定时提醒功能
const setupCheckReminder = () => {
  const checkReminder = () => {
    const now = new Date()
    const currentHour = now.getHours()
    const currentMinute = now.getMinutes()
    
    // 根据当前模式设置提醒时间
    if (currentMode.value === 'dormitory') {
      // 晚上查寝提醒
      if (currentHour === 22 && currentMinute === 0) {
        ElNotification({
          title: '查寝提醒',
          message: '现在是晚上9:30，该开始宿舍查寝了！',
          type: 'warning',
          duration: 0,
          position: 'top-right',
          onClick: () => {
            startCheck()
          }
        })
      }
    } else {
      // 上课考勤提醒（早上8:00）
      if (currentHour === 8 && currentMinute === 0) {
        ElNotification({
          title: '考勤提醒',
          message: '现在是早上8:00，该开始上课考勤了！',
          type: 'warning',
          duration: 0,
          position: 'top-right',
          onClick: () => {
            startCheck()
          }
        })
      }
    }
  }
  
  // 每分钟检查一次
  setInterval(checkReminder, 60000)
  
  // 立即检查一次（用于测试）
  checkReminder()
}

// 生成日总结
const generateDailySummary = () => {
  const today = new Date().toLocaleDateString('zh-CN')
  const todayRecords = currentHistory.value.filter(record => 
    record.date === today
  )
  
  if (todayRecords.length === 0) {
    ElMessage.warning('今天还没有' + (currentMode.value === 'dormitory' ? '查寝' : '考勤') + '记录')
    return
  }
  
  const latestRecord = todayRecords[todayRecords.length - 1]
  
  // 获取请假学生的详细信息
  const leaveStudents = latestRecord.students
    .filter(student => student.status === 'leave')
    .map(student => ({
      studentId: student.studentId,
      name: student.name,
      dormitory: student.dormitory || '未知'
    }))
  
  summaryData.value = {
    type: 'daily',
    date: today,
    total: latestRecord.total,
    present: latestRecord.present,
    absent: latestRecord.absent,
    leave: latestRecord.leave,
    late: latestRecord.late,
    delay: latestRecord.delay || 0,
    leaveStudents: leaveStudents, // 添加请假学生列表
    details: latestRecord.details,
    mode: currentMode.value
  }
  
  summaryType.value = 'daily'
  showSummaryDialog.value = true
}

// 生成周总结
const generateWeeklySummary = () => {
  const oneWeekAgo = new Date()
  oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)
  
  const weekRecords = currentHistory.value.filter(record => {
    const recordDate = new Date(record.date)
    return recordDate >= oneWeekAgo
  })
  
  if (weekRecords.length === 0) {
    ElMessage.warning('最近一周没有查寝记录')
    return
  }
  
  const weeklyStats = {
    type: 'weekly',
    startDate: oneWeekAgo.toLocaleDateString('zh-CN'),
    endDate: new Date().toLocaleDateString('zh-CN'),
    totalChecks: weekRecords.length,
    avgPresent: 0,
    avgAbsent: 0,
    avgLeave: 0,
    avgLate: 0,
    avgDelay: 0,
    records: weekRecords,
    mode: currentMode.value
  }
  
  // 计算平均值
  const totalPresent = weekRecords.reduce((sum, record) => sum + record.present, 0)
  const totalAbsent = weekRecords.reduce((sum, record) => sum + record.absent, 0)
  const totalLeave = weekRecords.reduce((sum, record) => sum + record.leave, 0)
  const totalLate = weekRecords.reduce((sum, record) => sum + record.late, 0)
  const totalDelay = weekRecords.reduce((sum, record) => sum + (record.delay || 0), 0)
  
  weeklyStats.avgPresent = Math.round(totalPresent / weekRecords.length)
  weeklyStats.avgAbsent = Math.round(totalAbsent / weekRecords.length)
  weeklyStats.avgLeave = Math.round(totalLeave / weekRecords.length)
  weeklyStats.avgLate = Math.round(totalLate / weekRecords.length)
  weeklyStats.avgDelay = Math.round(totalDelay / weekRecords.length)
  
  summaryData.value = weeklyStats
  summaryType.value = 'weekly'
  showSummaryDialog.value = true
}

// 导出总结
const exportSummary = () => {
  if (!summaryData.value) return
  
  let content = ''
  if (summaryType.value === 'daily') {
    content = `班级查寝日总结\n`
    content += `日期：${summaryData.value.date}\n`
    content += `总人数：${summaryData.value.total}人\n`
    content += `在寝人数：${summaryData.value.present}人\n`
    content += `缺勤人数：${summaryData.value.absent}人\n`
    content += `请假人数：${summaryData.value.leave}人\n`
    content += `迟到人数：${summaryData.value.delay}人\n`
    content += `晚归人数：${summaryData.value.late}人\n`
    content += `在寝率：${Math.round((summaryData.value.present / summaryData.value.total) * 100)}%\n`
    
    // 添加请假学生名单
    if (summaryData.value.leaveStudents && summaryData.value.leaveStudents.length > 0) {
      content += `\n请假学生名单：\n`
      summaryData.value.leaveStudents.forEach(student => {
        content += `寝室号：${student.dormitory}，姓名：${student.name}，学号：${student.studentId}\n`
      })
    }
  } else {
    content = `班级查寝周总结\n`
    content += `统计周期：${summaryData.value.startDate} 至 ${summaryData.value.endDate}\n`
    content += `查寝次数：${summaryData.value.totalChecks}次\n`
    content += `平均在寝人数：${summaryData.value.avgPresent}人\n`
    content += `平均缺勤人数：${summaryData.value.avgAbsent}人\n`
    content += `平均请假人数：${summaryData.value.avgLeave}人\n`
    content += `平均迟到人数：${summaryData.value.avgDelay}人\n`
    content += `平均晚归人数：${summaryData.value.avgLate}人\n`
  }
  
  // 创建并下载文件
  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `查寝${summaryType.value === 'daily' ? '日' : '周'}总结_${new Date().toLocaleDateString('zh-CN')}.txt`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  
  ElMessage.success('总结已导出')
}

// Excel文件处理
const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return

  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      // 使用xlsx库解析Excel文件
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })
      
      // 获取第一个工作表
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      
      // 将工作表转换为JSON数据
      const jsonData = XLSX.utils.sheet_to_json(worksheet)
      
      if (jsonData.length === 0) {
        importResult.value = {
          success: false,
          message: 'Excel文件为空或没有数据'
        }
        return
      }
      
      // 解析学生数据（适配宿舍号、姓名、学号、联系方式格式）
      const students = []
      let invalidRows = 0
      
      jsonData.forEach((row, index) => {
        // 获取列数据（支持多种标题变体）
        const dormitory = currentMode.value === 'dormitory' ? (row['宿舍号'] || row['宿舍'] || row['dormitory'] || '') : ''
        const name = row['姓名'] || row['名字'] || row['name'] || ''
        const studentId = row['学号'] || row['学生学号'] || row['studentId'] || ''
        const contact = row['联系方式'] || row['联系电话'] || row['电话'] || row['contact'] || ''
        
        // 验证必要字段
        if (name && studentId) {
          students.push({
            dormitory: dormitory.toString(),
            name: name.toString(),
            studentId: studentId.toString(),
            contact: contact.toString()
          })
        } else {
          invalidRows++
        }
      })
      
      if (students.length === 0) {
        importResult.value = {
          success: false,
          message: '未找到有效的学生数据，请检查Excel格式'
        }
        return
      }
      
      importData.value = students
      importResult.value = {
        success: true,
        message: `成功读取 ${students.length} 条学生记录${invalidRows > 0 ? `，跳过 ${invalidRows} 条无效记录` : ''}`
      }
      
    } catch (error) {
      console.error('Excel解析错误:', error)
      importResult.value = {
        success: false,
        message: `文件解析失败：${error.message}，请检查文件格式`
      }
    }
  }
  reader.onerror = () => {
    importResult.value = {
      success: false,
      message: '文件读取失败，请重试'
    }
  }
  reader.readAsArrayBuffer(file)
}

// 确认导入
const confirmImport = () => {
  if (importData.value.length === 0) return
  
  // 清空现有数据（移除初始演示数据）
  currentStudents.value = []
  
  // 将导入的数据添加到学生列表
  importData.value.forEach(student => {
    currentStudents.value.push({
      ...student,
      id: Date.now() + Math.random(),
      checkStatus: 'unchecked',
      lastCheckTime: null
    })
  })
  
  hasUnsavedChanges.value = true
  showImportDialog.value = false
  const importedCount = importData.value.length
  importData.value = []
  importResult.value = null
  
  ElMessage.success(`成功导入 ${importedCount} 条学生记录，已清空原有数据`)
}

// 跳转到班级考勤页面
const goToClassAttendance = () => {
  // 切换模式
  currentMode.value = currentMode.value === 'dormitory' ? 'class' : 'dormitory'
  
  // 重置检查状态
  if (isChecking.value) {
    isChecking.value = false
  }
  
  // 清空选择
  selectedStudents.value = []
  
  ElMessage({
    message: `已切换到${currentMode.value === 'dormitory' ? '宿舍查寝' : '班级考勤'}模式`,
    type: 'success'
  })
}

// 生命周期
onMounted(() => {
  loadData()
  setupCheckReminder()
  applyTheme() // 应用主题
})
</script>

<style scoped>
.dormitory-check-app {
  height: 100vh;
  background-color: #f5f7fa;
}

.app-header {
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}

.header-content h1 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-card.present {
  background-color: #f0f9ff;
  border-color: #b3d8ff;
}

.stat-card.absent {
  background-color: #fff2f0;
  border-color: #ffccc7;
}

.stat-card.leave {
  background-color: #fffbe6;
  border-color: #ffe58f;
}

.stat-card.delay {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.student-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.batch-operation-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.quick-actions-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.quick-actions-title {
  color: white;
  font-size: 18px;
  font-weight: bold;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
  margin-bottom: 5px;
}

.quick-actions-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.quick-action-btn {
  min-width: 120px;
  height: 45px;
  font-size: 14px;
  font-weight: 600;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  transition: all 0.3s ease;
}

.quick-action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0,0,0,0.2);
}

.finish-action-group {
  display: flex;
  align-items: center;
}

.finish-check-btn {
  min-width: 150px;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
  border-radius: 10px;
  box-shadow: 0 6px 16px rgba(82, 196, 26, 0.3);
  transition: all 0.3s ease;
}

.finish-check-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(82, 196, 26, 0.4);
}

@media (max-width: 768px) {
  .batch-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .quick-actions-buttons {
    justify-content: center;
  }
  
  .finish-action-group {
    justify-content: center;
  }
}

/* 按寝室分排样式 */
.room-arrangement-card {
  margin-bottom: 20px;
}

.progress-info {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.progress-text {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}

/* 增强进度条中span文字的对比度 */
.el-progress__text span {
  color: #303133 !important;
  font-weight: 600 !important;
}

/* 确保所有进度条内的span都有良好对比度 */
.el-progress .el-progress__text span {
  color: #303133 !important;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8) !important;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.room-filter-row {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.room-display-row {
  max-height: 400px;
  overflow-y: auto;
}

.room-column {
  margin-bottom: 15px;
}

.room-card {
  height: 100%;
  min-height: 200px;
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.room-stats {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  justify-content: center;
}

.room-number {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.room-students {
  margin-bottom: 15px;
  min-height: 80px;
}

.room-student-item {
  margin-bottom: 8px;
  display: inline-block;
  margin-right: 8px;
}

.room-actions {
  text-align: center;
  padding-top: 10px;
  border-top: 1px solid #e4e7ed;
}

.room-actions .el-button-group {
  display: flex;
  justify-content: center;
}

/* 增强学生信息span的对比度 */
.student-id,
.student-name,
.dormitory-number {
  color: #303133 !important;
  font-weight: 500 !important;
}

/* 暗黑主题下的学生信息增强 */
body.dark-theme .student-id,
body.dark-theme .student-name,
body.dark-theme .dormitory-number {
  color: var(--dark-text-primary) !important;
  font-weight: 500 !important;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .room-column {
    flex: 0 0 50%;
    max-width: 50%;
  }
}

@media (max-width: 768px) {
  .room-column {
    flex: 0 0 100%;
    max-width: 100%;
  }
  
  .room-filter-row {
    flex-direction: column;
    gap: 10px;
  }
  
  .room-filter-row .el-col {
    width: 100%;
  }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
  .app-header {
    padding: 10px 15px;
  }
  
  .header-content h1 {
    font-size: 20px;
  }
  
  .header-actions {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .header-actions .el-button {
    padding: 8px 12px;
    font-size: 12px;
  }
  
  .header-actions .el-select {
    width: 100px !important;
  }
  
  .stats-row {
    margin-bottom: 15px;
  }
  
  .stats-row .el-col {
    margin-bottom: 10px;
  }
  
  .stat-card {
    padding: 15px 10px;
  }
  
  .stat-number {
    font-size: 24px;
  }
  
  .stat-icon {
    font-size: 24px;
  }
  
  .batch-operation-bar {
    padding: 15px;
    margin-bottom: 15px;
  }
  
  .batch-actions {
    gap: 15px;
  }
  
  .quick-actions-title {
    font-size: 16px;
  }
  
  .quick-action-btn {
    min-width: 100px;
    height: 40px;
    font-size: 12px;
  }
  
  .finish-check-btn {
    min-width: 120px;
    height: 45px;
    font-size: 14px;
  }
  
  .room-card {
    min-height: 150px;
  }
  
  .room-header {
    padding: 8px 0;
  }
  
  .room-number {
    font-size: 14px;
  }
  
  .room-stats {
    gap: 4px;
  }
  
  .room-stats .el-tag {
    font-size: 10px;
    padding: 2px 6px;
  }
  
  .room-students {
    min-height: 60px;
  }
  
  .room-student-item {
    margin-bottom: 6px;
    margin-right: 6px;
  }
  
  .room-student-item .el-tag {
    font-size: 11px;
  }
  
  .room-actions .el-button-group {
    flex-wrap: wrap;
    gap: 5px;
  }
  
  .room-actions .el-button {
    font-size: 11px;
    padding: 6px 10px;
  }
}

/* 平板设备优化 */
@media (min-width: 769px) and (max-width: 1024px) {
  .header-actions {
    gap: 10px;
  }
  
  .header-actions .el-button {
    padding: 10px 14px;
    font-size: 13px;
  }
  
  .stats-row .el-col {
    padding: 0 8px;
  }
  
  .stat-card {
    padding: 18px 12px;
  }
  
  .stat-number {
    font-size: 28px;
  }
  
  .batch-operation-bar {
    padding: 18px;
  }
  
  .quick-action-btn {
    min-width: 110px;
    height: 42px;
    font-size: 13px;
  }
  
  .room-column {
    margin-bottom: 12px;
  }
  
  .room-card {
    min-height: 180px;
  }
}

/* 现代UI增强效果 */
.app-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.header-content h1 {
  background: linear-gradient(45deg, #ffffff, #f0f0f0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.stat-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  border-radius: 16px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(0,0,0,0.15);
}

.stat-card.present {
  background: linear-gradient(135deg, rgba(240, 249, 255, 0.95), rgba(179, 216, 255, 0.3));
  border-color: rgba(64, 158, 255, 0.3);
}

.stat-card.absent {
  background: linear-gradient(135deg, rgba(255, 242, 240, 0.95), rgba(255, 204, 199, 0.3));
  border-color: rgba(245, 108, 108, 0.3);
}

.stat-card.leave {
  background: linear-gradient(135deg, rgba(255, 251, 230, 0.95), rgba(255, 229, 143, 0.3));
  border-color: rgba(230, 162, 60, 0.3);
}

.stat-card.delay {
  background: linear-gradient(135deg, rgba(230, 247, 255, 0.95), rgba(145, 213, 255, 0.3));
  border-color: rgba(64, 169, 255, 0.3);
}

.room-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  border-radius: 16px;
}

.room-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 40px rgba(0,0,0,0.15);
}

.room-header {
  background: linear-gradient(135deg, rgba(245, 247, 250, 0.8), rgba(255, 255, 255, 0.9));
  padding: 12px 16px;
  border-radius: 12px 12px 0 0;
  margin: -20px -20px 15px -20px;
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-card {
  animation: fadeInUp 0.6s ease-out;
}

.stat-card:nth-child(1) { animation-delay: 0.1s; }
.stat-card:nth-child(2) { animation-delay: 0.2s; }
.stat-card:nth-child(3) { animation-delay: 0.3s; }
.stat-card:nth-child(4) { animation-delay: 0.4s; }
.stat-card:nth-child(5) { animation-delay: 0.5s; }

/* 按钮现代效果 */
.header-actions .el-button {
  background: rgba(255, 255, 255, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.header-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.2);
}

.header-actions .el-button:active {
  transform: translateY(0);
}

</style>
